<!--
Date: 2025-08-13
Copyright (c) 2025 CAX Conversion Project
-->
<template>
  <el-dialog v-model="props.importVisible" title="参数导入" width="500" destroy-on-close @close="handleVisible('cancel')">
    <div class="import_div">
      <el-upload
        @change="handleChange"
        :on-remove="handleRemove"
        :file-list="fileList"
        :show-file-list="true"
        :auto-upload="false"
        :multiple="false"
        :limit="1"
        action="#"
        accept=".xls,.xlsx"
      >
        <el-button size="small" type="primary">选取文件</el-button>
      </el-upload>
      <div class="el-upload__tip">请选择要上传的文件，格式为xls,xlsx</div>
      <div class="error">
        <div v-for="item in errorData" :key="item">{{ item }}</div>
      </div>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button size="small" type="primary" @click="submitForm">确 定</el-button>
        <el-button size="small" @click="handleVisible('cancel')">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup >
import { importData } from '@/api/parameterLibrary';
const props = defineProps(['importVisible']);
const emits = defineEmits(['handleImportEvent']);
const fileList = ref([]);
const submitFile = ref(null);
const validate = ref(false);
const errorData = ref([]);

const handleVisible = (type) => {
  emits('handleImportEvent', { type: 'cancel' });
};
const handleRemove = (file) => {
  submitFile.value = null;
};
const handleChange = (file) => {
  const fileType = file.name.split('.');
  if (!(fileType[1] === 'xls' || fileType[1] === 'xlsx')) {
    ElMessage({ showClose: true, message: '文件类型错误', type: 'error' });
    return;
  }
  validate.value = true;
  submitFile.value = file.raw;
};
const submitForm = () => {
  if (validate.value) {
    const formData = new FormData();
    formData.append('file', submitFile.value);
    importData(formData).then((res) => {
      if (res) {
        errorData.value = res.msg?.split('<br/>');
        if (errorData.value.length > 0) {
          ElMessage({ showClose: true, message: '文件上传存在错误', type: 'warning' });
          return;
        }
        emits('handleImportEvent', { type: 'submit' });
        ElMessage({ showClose: true, message: '文件上传成功', type: 'success' });
      }
    });
  } else {
    ElMessage({ showClose: true, message: '文件类型错误', type: 'error' });
  }
};
</script>
<style lang="scss" scoped>
.import_div {
  // display: flex;
  align-items: center;
  .error {
    margin-top: 10px;
  }
}
</style>